import util from "../../utils/util";
import answerUtil from "../../utils/answerUtil";
Page({

  /**
   * 页面的初始数据
   */
  data: {
    gridItems: [
      {id: 1,value: 1},
      {id: 2,value: 2},
      {id: 3,value: 3},
      {id: 0,value: 0},
      {id: 4,value: 4},
      {id: 5,value: 5},
      {id: 6,value: 6},
      {id: 'minus',value: '-'},
      {id: 7,value: 7},
      {id: 8,value: 8},
      {id: 9,value: 9},
      {id: 'delete',value: '删除'}
    ],
    value: '',
    isShow: true,
    tabNum: -1,
    expression: '', // 存储生成的表达式
    result: null, // 存储正确结果
    totalCount: 0, //题目总数
    count: 0, //记录做题次数
    countdownTime: 60, // 倒计时时间
    countdownInterval: null, // 存储 interval ID
    questionIndex: 0, //当前题型索引
    questionStartTime: null,//记录题目开始时间
    answerRecords: [],//答题记录
  },
  onLoad() {
    this.getTopicData();
    this.generateExpression();
    // 初始化时加载已有的答题记录
    const savedAnswerRecords = answerUtil.getAnswerRecords();
    this.setData({
      answerRecords: savedAnswerRecords
    });
  },
  // 获取题目数量
  getTopicData() {
    const questionIndex = wx.getStorageSync('questionInfo').questionNumber;
    const {count} = util.getData(questionIndex);
    
    this.setData({
      totalCount: count,
      questionIndex
    })
  },
  // 生成表达式
  generateExpression() {
    const numCount = Math.random() > 0.5 ? 2 : 3; // 随机生成 2 或 3 个数字
    const numbers = [];

    for (let i = 0; i < numCount; i++) {
      numbers.push(Math.floor(Math.random() * 90) + 10); // 10 ~ 99
    }

    // 随机选择运算符
    const operators = [];
    for (let i = 0; i < numCount - 1; i++) {
      operators.push(Math.random() > 0.5 ? '+' : '-');
    }

    // 构建表达式字符串
    let expr = '';
    for (let i = 0; i < numbers.length; i++) {
      if (i === 0) {
        expr += numbers[i];
      } else {
        expr += ` ${operators[i - 1]} ${numbers[i]}`;
      }
    }

    // 计算正确答案
    const result = this.evaluateExpression(expr);

    this.setData({
      expression: expr,
      result: result,
      value: '',
      tabNum: -1,
      questionStartTime: new Date().getTime()
    });
     // 每道题目开始倒计时
     this.startCountdown();
  },
  // 计算答案
  evaluateExpression(expr) {
    expr = expr.replace(/\s+/g, '');
    const tokens = expr.match(/(\d+)|([+-])/g);

    if (!tokens) {
      throw new Error('无效表达式');
    }

    let result = parseInt(tokens[0], 10);
    let i = 1;

    while (i < tokens.length) {
      const op = tokens[i];
      const num = parseInt(tokens[i + 1], 10);

      if (op === '+') {
        result += num;
      } else if (op === '-') {
        result -= num;
      }

      i += 2;
    }

    return result;
  },
  // 倒计时
  startCountdown() {
    let that = this;
    let {totalCount,count} = that.data;
    // 清除已有倒计时
    if (that.data.countdownInterval) {
      clearInterval(that.data.countdownInterval);
    }
    that.setData({
      countdownTime: 60
    });
    const interval = setInterval(() => {
      let newTime = that.data.countdownTime - 1;
      if (newTime > 0) {
        that.setData({
          countdownTime: newTime
        });
      } else {
        clearInterval(interval);
        // 倒计时结束，视为错误
        wx.showToast({
          title: '已超时',
          icon: 'none',
          duration: 1000
        });
        setTimeout(() => {
          // 使用共用方法创建并保存答题记录
          const newAnswerRecords = that.createAndSaveAnswerRecord(true);
          // 无论对错都增加总次数
          let countNum = count + 1;
          that.setData({
            count:countNum,
            answerRecords: newAnswerRecords
          })
          // 判断题目次数，跳转并打印结果
          if (countNum >= totalCount) {
            //跳转下一题
            let questionNumber = this.data.questionIndex + 1;
            const prevInfo = wx.getStorageSync('questionInfo') || {};
            wx.setStorageSync('questionInfo', {
              ...prevInfo,
              questionNumber
            });
            util.navigateByDesc(questionNumber);
          } else {
            // 继续下一题
            that.generateExpression();
          }
        }, 1000);
      }
    }, 1000);
    that.setData({
      countdownInterval: interval
    });
  },
  // 点击键盘按钮
  onTap(e) {
    const key = e.currentTarget.dataset.value;
    let currentValue = this.data.value;
    if (key === 'delete') {
      this.setData({
        value: currentValue.slice(0, -1)
      })
    } else if (currentValue.length < 4) {
      if (key === 'minus') {
        this.setData({
          value: currentValue + '-'
        })
      } else {
        this.setData({
          value: currentValue + key
        });
      }
    }
    this.setData({
      tabNum: key
    })
  },
  // 提交
  onSubmit() {
    let {count,value, result,totalCount} = this.data;
    if (!value) return;
    const answer = parseInt(value, 10);
     // 无论对错都增加总次数
     let countNum = count + 1;
     let isCorrect;
     if (answer === result) {
      isCorrect = true
    }else{
      isCorrect = false
    }
    // 清除倒计时
    if (this.data.countdownInterval) {
      clearInterval(this.data.countdownInterval);
      this.setData({
        countdownInterval: null
      });
    }
    // 使用共用方法创建并保存答题记录
    const newAnswerRecords = this.createAndSaveAnswerRecord(false, value,isCorrect);
     this.setData({
       tabNum: -1,
       count: countNum,
       answerRecords: newAnswerRecords
     })

     if (countNum >= totalCount) {
        //跳转下一题
        let questionNumber = this.data.questionIndex + 1;
        const prevInfo = wx.getStorageSync('questionInfo') || {};
        wx.setStorageSync('questionInfo', {
          ...prevInfo,
          questionNumber
        });
        util.navigateByDesc(questionNumber);
    } else {
      this.generateExpression(); // 下一题
    }
    
  },
  // 处理答题记录
  createAndSaveAnswerRecord(isTimeout = false, userOption = '',isRight = false) {
    const {questionStartTime,questionIndex,result} = this.data;
    const questionList = wx.getStorageSync('questionInfo').questionList;
    const currentTopic = questionList[questionIndex]
    // 计算答题时间
    const endTime = new Date().getTime();
    const answerTime = answerUtil.calculateAnswerTime(questionStartTime, endTime);

    // 判断是否正确（超时视为错误）
    let option = '';
    if (!isTimeout) {
      option = userOption;
      isRight = isRight ? 1 : 0;
    }
    
    // 创建答题记录
    const answerRecord = answerUtil.createAnswerRecord({
      qosId: 0,
      anserTime: answerTime,
      isRight: isRight,
      option: option,
      classify: currentTopic.typeCode,
      stem: '',
      accuracy: '',
      timeStemp: endTime.toString(),
      everyTxt: '',
      rightOption: result.toString(),
      score: 0,
    });
    
    // 添加答题记录
    const newAnswerRecords = answerUtil.addAnswerRecord(answerRecord);
    
    return newAnswerRecords;
  },

  onUnload() {
    // 页面卸载时确保答题记录已保存
    answerUtil.saveAnswerRecords(this.data.answerRecords);
    if (this.data.countdownInterval) {
      clearInterval(this.data.countdownInterval);
      this.setData({
        countdownInterval: null
      });
    }
  }
})